<template>
  <div class="planList">
    <div class="mainCon">
      <div class="containercontent">
        <div class="seachTip selectw100">
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              名称
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-input style="" v-model="getPlanListParams.name" size="mini" placeholder="计划名称" @keyup.enter.native="getPlanList(planQuery,'search')"
                clearable></el-input>
            </div>
          </div>
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              类型
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="getPlanListParams.taskType" placeholder="请选择" size="mini" clearable @change="getPlanList(planQuery,'search')">
                <el-option v-for="item in reportWordList.itemList" :key="item.code" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="inlineblock verticalmiddle infoitem">
            <div class="inlineblock verticalmiddle">
              模板状态
            </div>
            <div class="inlineblock verticalmiddle informationItem">
              <el-select v-model="getPlanListParams.status" placeholder="请选择" size="mini" clearable @change="getPlanList(planQuery,'search')">
                <el-option v-for="item in enableStatus" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="inlineblock basicRightDistanceA searchIcon" style="padding-left:20px;">
            <el-button size="mini" @click="getPlanList(planQuery,'search')">搜索</el-button>
            <el-button size="mini" @click="emptySearch">清空</el-button>
          </div>
        </div>

        <div class="separaterowTable">
          <div class="tableTittle">
            <div><span class="fontImpact">1</span><span>任务模板</span></div>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="newPlan" style="float:right" v-if="userOpernation.add.display">添加模板</el-button>
          </div>
          <el-table :data="detectionPlanTableData.data" style="width: 100%" size="mini" class="tableCon tableColor" :cell-class-name="tableCellClassName">
            <el-table-column label="序号" min-width="50px">
              <template slot-scope="scope">
                {{scope.$index+(planQuery.page - 1) * planQuery.pageCount + 1}}
              </template>
            </el-table-column>
            <el-table-column property="name" label="名称"  min-width="150px" show-overflow-tooltip>
            </el-table-column>
            <el-table-column property="clientName" label="客户" min-width="100px" show-overflow-tooltip>
            </el-table-column>
            <el-table-column property="taskType" label="类型" :formatter="taskTypeFormatter" min-width="100px">
            </el-table-column>

            <el-table-column property="doAuto" label="自动下达" min-width="80px">
              <template slot-scope="scope">
                {{scope.row.doAuto==true?'是':'否'}}
              </template>
            </el-table-column>

            <el-table-column property="source" label="采样来源" min-width="80px">
              <template slot-scope="scope">
                {{scope.row.source==0?'采样':'送样'}}
              </template>
            </el-table-column>
            <el-table-column property="status" label="状态" min-width="90px" :formatter="formatter">
            </el-table-column>
            <el-table-column property="createTime" label="创建日期" min-width="145px">
              <template slot-scope="scope">
                {{scope.row.createTime.split('.')[0]}}
              </template>
            </el-table-column>

            <el-table-column label="操作" min-width="200px">
              <template slot-scope="scope">
                <el-button @click="checkDetectionPlan(scope.row)" type="text" size="mini" v-if="scope.row.status==3 && userOpernation.check.display">审核</el-button>
                <el-button @click="editStatus(scope.row)" type="text" size="mini" v-if="scope.row.status==1 && userOpernation.disable.display">停用</el-button>
                <el-button @click="editStatus(scope.row)" type="text" size="mini" v-if="scope.row.status==0 && userOpernation.enable.display">启用</el-button>
                <el-button @click="editDetectionPlan(scope.row)" type="text" size="mini" v-if="(scope.row.status==2||scope.row.status==4) && userOpernation.update.display">编辑</el-button>
                <el-button @click="lookDetectionPlan(scope.row)" type="text" size="mini" v-if="userOpernation.select.display">详情</el-button>
                <el-button type="text" size="small" @click="buttonClick(scope.row,'模板复制')" v-if="userOpernation.add.display">复制</el-button>

                <el-button type="text" size="mini" @click="deleteDetectionPlan(scope.row)" v-if="(scope.row.status==2||scope.row.status==4) && userOpernation.delete.display">删除</el-button>
                <el-button type="text" size="mini" @click="deleteDetectionPlan(scope.row)" v-if="(scope.row.status !=2 && scope.row.status!=4) && userOpernation.systemDelete.display">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block changepages">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="planQuery.page" :page-sizes="[20, 30, 40]"
              :page-size="planQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div>
      <taskdetail v-if="taskDetailShow" :taskDetailShow="taskDetailShow" :getPlanData='getPlanData' :type='taskdetailType' :title='title'
        :showTabIndex='showTabIndex' :showButton.sync='showButton' :isPlan="true">
      </taskdetail>
      <!--添加模板弹框-->
      <newTask :createType.sync='createType' :pnowTab.sync='nowTab' :newTaskTitle.sync='newTaskTitle' :newTaskShow.sync='thisNewTaskShow'
        :newTaskData.sync='thisNewTaskData'></newTask>
    </div>
    <div v-if="againconfirmShow">
      <againconfirm :model = "'dectionCopy'"></againconfirm>
    </div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  const taskdetail = () => import('../taskPlanManage/children/taskDetail/taskDetail.vue');
  const newTask = () => import('./taskTemplateChildren/newTask.vue');
  const againconfirm = () => import('./children/againConfirm.vue');

  export default {
    data() {
      return {
        getPlanListParams: {
          name: '',
          taskType: '',
          status: '',
        },
        planQuery: {
          page: 1,
          pageCount: 20,
        },
        rowNumber: 0, //总条数


        createType: '',
        nowTab: '',
        newTaskTitle: {},
        thisNewTaskShow: false,
        thisNewTaskData: {
          newTaskBasic: {
            "name": "",
            "code": "",
            "taskType": "",
            "reportWord": "",
            "client": "",
            "doAuto": false,
            "doBlind": false,
            "source": 0,
            "status": 2,
            "sampleBeans": [],
            "offices":'ALL',
          },
          newTaskPointList: [],
          newTaskItemList: [],
          newTaskMeterialList: []
        },
        showButton: {},
        showTabIndex: [],
        getPlanData: {},
        detectionPlanTableData: {},
        enableStatusValue: '',
        searchName: '',
        analysisItemTypeValue: '',
        roundingTypeValue: '',
        currentPage: 1,
        entrustmentUnitValue: '',
        planName: '',
        taskDetailShow: false,
        taskdetailType: 'plan',//任务详情的类型
        title: '添加模板',
        taskTypeTableDateValue: '',
        cycStatusValue: '',
        againconfirmShow:false,

      }
    },
    props: ['userOpernation'],

    components: {
      taskdetail, newTask,againconfirm
    },
    computed: {
      ...mapState(['daibanItemShow','tableHeightA', 'enableStatus', 'tableHeightB', 'analysisItemType', 'roundingType', 'yesorno', 'entrustmentUnit', 'taskTypeTableDate', 'cycStatus', 'reportWordList','daibanItem']),
    },
		created(){
				if(this.daibanItemShow){
					this.checkDetectionPlan(this.daibanItem)
					this.$store.commit('passDaibanItemShow', false)
			}

		},
    mounted() {
      this.$store.dispatch('dogetDictionary')
      this.$store.dispatch('taskCommonQuery')
      this.$store.dispatch('getAllClients')
      this.$store.dispatch('getEmployeeByLab')
      this.getPlanList(this.planQuery)
    },
    watch: {
				daibanItem(newer,older){
						if(this.daibanItemShow){
							this.checkDetectionPlan(this.daibanItem)
							this.$store.commit('passDaibanItemShow', false)
					}
				},
      planQuery: {
        handler(val, oldVal) {
          this.getPlanList(this.planQuery)
        },
        deep: true
      },
    },
    methods: {
      // 状态
      formatter(row, column, cellValue) {
        return this.util.changeStatus({ cellValue: cellValue, list: this.enableStatus })

      },
      tableRowClassName({ row, column, rowIndex, columnIndex }) {
        if (row.status == 0 && columnIndex == 6) {
      	  return "colorRed"
        }
      },
      // 任务类型
      taskTypeFormatter(row, column, cellValue, index) {
        let filterArr = [];
        if (this.reportWordList.length == 0) {
          return cellValue
        }
        filterArr = this.reportWordList.itemList.filter(item => item.code == cellValue)
        if (filterArr.length != 0) {
          return filterArr[0].name
        }

      },
      tableCellClassName({ row, column, rowIndex, columnIndex }) {
        //  4.已驳回
        if (row.status == '4' && columnIndex == 6) {
          return "color"
        }
        if (row.status == 0 && columnIndex == 6) {
          return "colorRed"
        }

      },
      // 启用和停用
      editStatus(row) {
        var msg = row.status == 0 ? "启用" : "停用";
        this.$confirm("是否" + msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            method: 'post',
            apiUrl: '/detection/updatePlanInfo.htm',
            params: { id: row.id, status: row.status == 0 ? 1 : 0 },
            isJson: true,
          }).then(res => {
            if (res.code === 0) {
              if (row.status == 0) {
                this.$set(row, 'status', 1)
              } else if (row.status == 1) {
                this.$set(row, 'status', 0)
              }
              this.$message({
                showClose: true,
                message: '修改成功！',
                type: 'success'
              })
            } else {
              this.$message({
                showClose: true,
                message: '修改失败！',
                type: 'error'
              })
            }
          }, )
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消' + msg
          });
        });

      },
      // 清空
      emptySearch() {
        this.getPlanListParams = {
          name: '',
          taskType: '',
          status: '',
        }
        this.getPlanList(this.planQuery,'search');
      },
      // 搜索
      // doSearch() {
      //   this.getPlanList();
      // },
      getPlanList(parp,search) {
        var params = {
          name: this.getPlanListParams.name,
          taskType: this.getPlanListParams.taskType,
          status: this.getPlanListParams.status,
        }
        if(search !=undefined){
					this.planQuery.page = 1;
					params.page =  1;
					params.pageCount = parp.pageCount;
				}else{
					params.page =  parp.page;
					params.pageCount = parp.pageCount;
				}

        this.$http({
          method: 'post',
          apiUrl: '/detection/getPlanList.htm',
          params: params,
          isJson: true,
        }).then(res => {
          if (res.code === 0) {
            this.detectionPlanTableData = res;
            if (!res.pageinfo) {
              this.rowNumber = 0;
            } else if (res.pageinfo && !res.pageinfo.rowNumber) {
              this.rowNumber = 0;
            } else {
              this.rowNumber = res.pageinfo.rowNumber;
            }
          }
        })
      },

      callTaskDetail(title, showTabIndex) {
        this.title = title
        this.showTabIndex = showTabIndex
        this.taskDetailShow = true;
        this.getPlanData = this.thisNewTaskData.newTaskBasic

        console.log(this.getPlanData)
      },
      // 把数据中的sampleBeans转为planSampleBeans
      changeData(data) {
        data.planSampleBeans = data.sampleBeans;

        return data;
      },

      newPlan: function () {
        this.thisNewTaskShow = true
        this.thisNewTaskData = {
          newTaskBasic: {
            "name": "",
            "code": "",
            "taskType": "",
            "reportWord": "",
            "client": "",
            "doAuto": false,
            "doBlind": false,
            "source": 0,
            "status": 2,
            "sampleBeans": [],
            "offices":'ALL',
            "timeExpression": {
              "id": "",
              "businessId": "",
              "hours": [],
              "day": [],
              "month": [],
              "week": [],
              "year": ""
            }
          },
          newTaskPointList: [],
          newTaskItemList: [],
          newTaskMeterialList: []
        };
        this.nowTab = 'taskBasicInfo';
        this.newTaskTitle = {
          taskBasicInfo: '任务导航-第一步-任务基础信息',
          selectCheckPiont: '任务导航-第二步-选择监测点',
          addQc: '任务导航-第三步-添加现场质控',
          addCheckItem: '任务导航-第四步-添加检测项目',
          sampleInfo: '任务导航-第五步-样品信息',

        };

        this.createType = '添加模板'

      },
      editDetectionPlan: function (row) {
        this.title = "编辑模板"
        this.showButton = {
          saveButton: true,
          submitButton: true,
          auditButton: false
        }
        if(row.status == 4){
          this.showButton.saveButton = false;
        }
        this.showTabIndex = [0, 1, 5]
        this.getPlan(row).then((res) => {
          this.getPlanData = res.data;
          if (!this.getPlanData.timeExpression) {
            this.getPlanData.timeExpression = {
              "id": "",
              "businessId": this.getPlanData.id,
              "hours": [],
              "day": [],
              "month": [],
              "week": [],
              "year": ""
            }
          } else {
            // 如果返回的是空字符串,直接赋值为空数组，否则把字符串截取为数组
            if (this.getPlanData.timeExpression.hours != "") {
              this.getPlanData.timeExpression.hours = this.getPlanData.timeExpression.hours.split(',')
            } else {
              this.getPlanData.timeExpression.hours = [];
            }
            if (this.getPlanData.timeExpression.day != "") {
              this.getPlanData.timeExpression.day = this.getPlanData.timeExpression.day.split(',')
            } else {
              this.getPlanData.timeExpression.day = [];
            }
            if (this.getPlanData.timeExpression.month != "") {
              this.getPlanData.timeExpression.month = this.getPlanData.timeExpression.month.split(',')
            } else {
              this.getPlanData.timeExpression.month = [];
            }
            if (this.getPlanData.timeExpression.week != "") {
              this.getPlanData.timeExpression.week = this.getPlanData.timeExpression.week.split(',')
            } else {
              this.getPlanData.timeExpression.week = [];
            }


          }
          this.taskDetailShow = true;
        }, (err) => {
          console.log(err)
        })

      },
      checkDetectionPlan: function (row) {
        this.title = "模板审核"
        this.showButton = {
          saveButton: false,
          submitButton: false,
          auditButton: false,
          checkButton: true
        }
        this.showTabIndex = [0, 1, 5]
        this.getPlan(row).then((res) => {
          this.getPlanData = res.data;
          if (!this.getPlanData.timeExpression) {
            this.getPlanData.timeExpression = {
              "id": "",
              "businessId": this.getPlanData.id,
              "hours": [],
              "day": [],
              "month": [],
              "week": [],
              "year": ""
            }
          } else {

            // 如果返回的是空字符串,直接赋值为空数组，否则把字符串截取为数组
            if (this.getPlanData.timeExpression.hours != "") {
              this.getPlanData.timeExpression.hours = this.getPlanData.timeExpression.hours.split(',')
            } else {
              this.getPlanData.timeExpression.hours = [];
            }
            if (this.getPlanData.timeExpression.day != "") {
              this.getPlanData.timeExpression.day = this.getPlanData.timeExpression.day.split(',')
            } else {
              this.getPlanData.timeExpression.day = [];
            }
            if (this.getPlanData.timeExpression.month != "") {
              this.getPlanData.timeExpression.month = this.getPlanData.timeExpression.month.split(',')
            } else {
              this.getPlanData.timeExpression.month = [];
            }
            if (this.getPlanData.timeExpression.week != "") {
              this.getPlanData.timeExpression.week = this.getPlanData.timeExpression.week.split(',')
            } else {
              this.getPlanData.timeExpression.week = [];
            }

          }
          this.taskDetailShow = true;
        }, (err) => {
          console.log(err)
        })

      },
      lookDetectionPlan(row) {
        this.title = "查看模板";
        this.showTabIndex = [0, 1,4, 5]
        this.showButton = {
          saveButton: false,
          submitButton: false,
          auditButton: false
        }
        this.getPlan(row).then((res) => {

          this.getPlanData = res.data;
          if (!this.getPlanData.timeExpression) {
            this.getPlanData.timeExpression = {
              "id": "",
              "businessId": this.getPlanData.id,
              "hours": [],
              "day": [],
              "month": [],
              "week": [],
              "year": ""
            }
          } else {
            // 如果返回的是空字符串,直接赋值为空数组，否则把字符串截取为数组
            if (this.getPlanData.timeExpression.hours != "") {
              this.getPlanData.timeExpression.hours = this.getPlanData.timeExpression.hours.split(',')
            } else {
              this.getPlanData.timeExpression.hours = [];
            }
            if (this.getPlanData.timeExpression.day != "") {
              this.getPlanData.timeExpression.day = this.getPlanData.timeExpression.day.split(',')
            } else {
              this.getPlanData.timeExpression.day = [];
            }
            if (this.getPlanData.timeExpression.month != "") {
              this.getPlanData.timeExpression.month = this.getPlanData.timeExpression.month.split(',')
            } else {
              this.getPlanData.timeExpression.month = [];
            }
            if (this.getPlanData.timeExpression.week != "") {
              this.getPlanData.timeExpression.week = this.getPlanData.timeExpression.week.split(',')
            } else {
              this.getPlanData.timeExpression.week = [];
            }
          }
          this.taskDetailShow = true;
        }, (err) => {
          console.log(err)
        })
      },
      deleteDetectionPlan(row) {
        this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            method: 'post',
            apiUrl: '/detection/deletePlan.htm',
            params: { id: row.id },
            isJson: false,
          }).then(res => {
            if (res.code === 0) {

              this.$message({
                showClose: true,
                message: '删除成功！',
                type: 'success'
              })
              this.getPlanList(this.planQuery)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      getPlan(row) {
        return new Promise((resolve, reject) => {
          this.$http({
            method: 'post',
            apiUrl: '/detection/getPlan.htm',
            params: { id: row.id },
            isJson: false,
          }).then(res => {
            if (res.code === 0) {
              resolve(res)
            }
          })
        })
      },
      // 任务复制
      buttonClick(row,title){
        this.getPlan(row).then(res => {
          delete res.data.id;
          delete res.data.status;
          for(var i in res.data.sampleBeans){
             delete res.data.sampleBeans[i].id
             delete res.data.sampleBeans[i].status
             delete res.data.sampleBeans[i].deleteFlag
             for(var j in res.data.sampleBeans[i].detectBeans){
               delete res.data.sampleBeans[i].detectBeans[j].id
               delete res.data.sampleBeans[i].detectBeans[j].status
               delete res.data.sampleBeans[i].detectBeans[j].deleteFlag
               var obj =  res.data.sampleBeans[i].detectBeans[j]
               for(var k in obj.itemBeans){
                delete obj.itemBeans[k].id
                delete obj.itemBeans[k].status
               }

             }
          }
          this.thisNewTaskData.newTaskBasic = res.data
          this.getPlanData = res.data;
          if (!this.getPlanData.timeExpression) {
            this.getPlanData.timeExpression = {
              "id": "",
              "businessId": this.getPlanData.id,
              "hours": [],
              "day": [],
              "month": [],
              "week": [],
              "year": ""
            }
          } else {
            // 如果返回的是空字符串,直接赋值为空数组，否则把字符串截取为数组
            if (this.getPlanData.timeExpression.hours != "") {
              this.getPlanData.timeExpression.hours = this.getPlanData.timeExpression.hours.split(',')
            } else {
              this.getPlanData.timeExpression.hours = [];
            }
            if (this.getPlanData.timeExpression.day != "") {
              this.getPlanData.timeExpression.day = this.getPlanData.timeExpression.day.split(',')
            } else {
              this.getPlanData.timeExpression.day = [];
            }
            if (this.getPlanData.timeExpression.month != "") {
              this.getPlanData.timeExpression.month = this.getPlanData.timeExpression.month.split(',')
            } else {
              this.getPlanData.timeExpression.month = [];
            }
            if (this.getPlanData.timeExpression.week != "") {
              this.getPlanData.timeExpression.week = this.getPlanData.timeExpression.week.split(',')
            } else {
              this.getPlanData.timeExpression.week = [];
            }


          }
          this.againconfirmShow = true
        })
      },

      changeDetectionPlanStatus: function (row) {
        console.log(row);
      },
      editAnalysisItem: function (row) {
        console.log(row);
      },
      handleSizeChange: function (val) {
        this.planQuery.pageCount = val;
      },
      handleCurrentChange: function (val) {
        this.planQuery.page = val;
      },
      changeDefaultTask: function (row, type) {
        let attribute = type == 'week' ? 'isDefaultWeekTask' : 'isDefaultDayTask';
        row[attribute] = row[attribute] == '1' ? '0' : '1';
      }
    }
  }

</script>

<!--Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .seachTip .informationItem {
    width: calc(100% - 60px);
  }

  .seachTip .infoitem {
    width: calc(100%/4);
    padding-right:0;
  }
</style>
<style>
  .planList .tableColor .color {
    color: #faa646;
  }
  .planList .colorRed{
    color:red
  }
</style>
